package com.mcptt.config.ue.initial;

import com.cloudptt.api.product.log.Log;
import com.mcptt.config.AbstractConfigFile;
import com.mcptt.config.callback.IParserCallback;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.BootStrapSvrInfo;
import com.mcptt.config.ue.initial.sub.DefaultUserProfile;
import com.mcptt.config.ue.initial.sub.McpttUeId;
import com.mcptt.config.ue.initial.sub.OnNetwork;
import com.mcptt.config.ue.initial.sub.sub.AnyExt;
import com.mcptt.config.ue.initial.sub.sub.AppServerInfo;
import com.mcptt.db.DBAdapter;
import com.mcptt.db.model.ConfigFileInfo;
import com.mcptt.notify.xcap.XcapDoc;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.util.List;

public class UeInitProfile extends AbstractConfigFile implements IUeInitAttr
{
	//	public static final int FileType = 1;

	public static final String FileName = "org.3gpp.mcptt.ue-init-config";
	//	private static final String FilePath = "//config//";
	public static final String Name = "mcptt-UE-initial-configuration";
	private static final String Name_Domain = "domain";
	//	private static final String Name_SchemaLocation = "schemaLocation";
	//	private static final String Name_Xsi = "xmlns:xsi";
	//	private static final String Name_Xmlns = "xmlns";
	private static final String Name_Name = "name";
	private String domain = SysConfig.Default_Domain;
	//	private String schemaLocation = null;
	//	private String xsi = null;
	//	private String xmlns = null;


	private McpttUeId mcpttUeId = null;
	private DefaultUserProfile defaultUserProfile = null;
	private String name = null;
	private OnNetwork onNetwork = null;
	private IParserCallback parserCallback = null;



	//	public UeInitProfile(DBAdapter dbOperator, BootStrapSvrInfo serverInfo, String clientId, IParserCallback parserCallback)
//	{
//		super(dbOperator);
//		this.parserCallback = parserCallback;
////		this.info = readFromDb(FileName);
////		if(info == null)
////		{
//		Log.debug(this.getClass(),"UeInitProfile serverInfo = " + serverInfo);
//			XcapDoc doc = XcapDoc.getUeInitProfileXcapDoc(clientId);
//			String cmsUrl = serverInfo.toInitHttpUrl();
//			Log.debug(this.getClass(),"cmsUrl = " + cmsUrl);
//			runReadFromSvrThread(doc,cmsUrl,null,parserCallback);
////		}
////		else {
////			parse(info);
////		}
//	}
	public UeInitProfile(DBAdapter dbOperator, BootStrapSvrInfo serverInfo, String mcId, IParserCallback parserCallback)
	{
		super(dbOperator);
		this.parserCallback = parserCallback;
//		this.info = readFromDb(FileName);
//		if(info == null)
//		{
		Log.debug(this.getClass(),"UeInitProfile serverInfo = " + serverInfo);
//	XcapDoc doc = XcapDoc.getUeInitProfileXcapDoc(clientId);
		XcapDoc doc = XcapDoc.getUeInitProfileXcapDoc(mcId);
		String cmsUrl = serverInfo.toInitHttpUrl();
		Log.debug(this.getClass(),"cmsUrl = " + cmsUrl);
		runReadFromSvrThread(doc,cmsUrl,null,parserCallback);
//		}
//		else {
//			parse(info);
//		}
	}

	public void parse(ConfigFileInfo info)
	{
		if(info == null)
		{
			return;
		}

		SAXBuilder builder = new SAXBuilder();
		String content = info.getContent();
		ByteArrayInputStream strIs = new  ByteArrayInputStream(content.getBytes());
		try {
			Document document = builder.build(strIs);
			Element root = document.getRootElement();//锟斤拷酶锟斤拷诘锟�<bookstore>
			if(root == null)
			{
				return;
			}
			domain = root.getAttributeValue(Name_Domain);
			Log.debug(this.getClass(), "domain = " + domain);
			//		Namespace ns = root.getNamespace();
			//		schemaLocation = root.g.getAttributeValue(Name_SchemaLocation, ns);
			//		schemaLocation = root.getAttributeValue(Name_SchemaLocation);
			//		xsi = root.getAttributeValue(Name_Xsi);
			//		xmlns = root.getAttributeValue(Name_Xmlns);

			List<Element> list = root.getChildren();//锟斤拷酶锟斤拷诘锟斤拷锟接节碉拷
			for(Element elem:list)
			{
				String name = elem.getName();
				Log.debug(this.getClass(), "name = " + name);
				if(name == null
						|| name.length() <= 0)
				{
					return;
				}
				if(name.equals(McpttUeId.Name))
				{
					mcpttUeId = new McpttUeId();
					mcpttUeId.parse(elem);
				}
				else if(name.equals(DefaultUserProfile.Name))
				{
					defaultUserProfile = new DefaultUserProfile();
					defaultUserProfile.parse(elem);
				}
				else if(name.equals(Name_Name))
				{
					this.name = elem.getText();
				}
				else if(name.equals(OnNetwork.Name))
				{
					onNetwork = new OnNetwork();
					onNetwork.parse(elem);
				}
			}
		}catch (Exception e)
		{
			e.printStackTrace();
			notifyFailed(parserCallback,FileName,"UserProfile parse Exception = " + e);
		}

	}

	public String toString()
	{
		StringBuffer strBuf = new StringBuffer("\r\n");
		strBuf.append("<").append(Name);
		strBuf.append(" ").append(Name_Domain).append("=\"").append(domain).append("\" ");
		//		strBuf.append(" ").append(Name_SchemaLocation).append("=\"").append(schemaLocation).append("\" ");
		//		strBuf.append(" ").append(Name_Xsi).append("=\"").append(xsi).append("\" ");
		//		strBuf.append(" ").append(Name_Xmlns).append("=\"").append(xmlns).append("\" ");
		strBuf.append(">");

		strBuf.append(mcpttUeId);
		strBuf.append(defaultUserProfile);
		strBuf.append("    ").append("<").append(Name_Name).append(">");
		strBuf.append(name);
		strBuf.append("</").append(Name_Name).append(">").append("\r\n");
		strBuf.append(onNetwork);
		strBuf.append("</").append(Name).append(">");

		return strBuf.toString();
	}

	public OnNetwork getOnNetwork()
	{
		return onNetwork;
	}

	public boolean checkMustParamOk()
	{
		String psiGms = null;
		String psiMcPtt = null;
		String psiMcVideo = null;
		String psiMcData = null;
		String psiCms = null;
		AppServerInfo info = null;

		if(onNetwork != null) {
			psiGms = onNetwork.getGmsUri();//.getPsiGms();
			info = onNetwork.getAppServerInfo();

			if(onNetwork.getAnyExt() != null) {
				AnyExt anyExt = onNetwork.getAnyExt();
				Log.debug(this.getClass(), "checkMustParamOk anyExt = " + anyExt);
				if(anyExt.getMcpttPsi() != null) {
					psiMcPtt = anyExt.getMcpttPsi().getServerURI();
				}
				if(anyExt.getMcvideoPsi() != null) {
					psiMcVideo = anyExt.getMcvideoPsi().getServerURI();
				}
				if(anyExt.getMcdataPsi() != null) {
					psiMcData = anyExt.getMcdataPsi().getServerURI();
				}
				if(anyExt.getCmsPsi() != null) {
					psiCms = anyExt.getCmsPsi().getServerURI();
				}
			}
		}



		Log.debug(this.getClass(), "checkMustParamOk psiCms = " + psiCms + " psiGms = " + psiGms + " psiMcPtt = " + psiMcPtt + " psiMcVideo = " + psiMcVideo + " psiMcData = " + psiMcData+ " info = " + info);
		if(psiCms != null
				&& psiGms != null
				&& psiMcPtt != null
				&& psiMcVideo != null
				&& psiMcData != null
				&& info != null)
		{
			String cmsHttpUrl = info.getCms();
			String gmsHttpUrl = info.getGms();
//			String idmsHttpUrl = info.getIdms();
			String kmsHttpUrl = info.getKms();
			Log.debug(this.getClass(), "checkMustParamOk cmsHttpUrl = " + cmsHttpUrl + " gmsHttpUrl = " + gmsHttpUrl + " kmsHttpUrl = " + kmsHttpUrl);
			if(cmsHttpUrl != null
					&& gmsHttpUrl != null
//					&& idmsHttpUrl != null
					&& kmsHttpUrl != null)
			{
				return true;
			}
		}

		return false;
	}


	//	private ConfigFileInfo readFromLocFile() throws JDOMException,IOException,ConfigFailedException
	//	{
	//		Log.debug(getClass(), "readFromLocFile");
	//		File file = new File(Environment.getExternalStorageDirectory()+FilePath,FileName);
	//		if(!file.exists())
	//		{
	//			Log.debug(getClass(), "readFromLocFile file not exist");
	//			throw new ConfigFailedException("readFromLocFile","File not exist");
	//		}
	//		FileInputStream fis = new FileInputStream(file);
	//		String content = CommonFunc.convertStreamToString(fis);
	//		if(content == null
	//				|| content.equals(""))
	//		{
	//			Log.debug(getClass(), "readFromLocFile Content is null");
	//			throw new ConfigFailedException("readFromLocFile","Content is null");
	//		}
	//		return new ConfigFileInfo(FileName,"",content);
	//	}

	@Override
	public void syncToSvr()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void saveInfoToDb()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public CallTimer getCallTimer() {
		// TODO Auto-generated method stub
		if(onNetwork != null
				&& onNetwork.getTimers() != null)
		{
			return onNetwork.getTimers().toCallTimer();
		}
		return null;
	}
	public String getDomain() {
		return domain;
	}
}
